#include <iostream>
#include <pthread.h>
#include <thread>
#include <chrono>
#include "Mutex.hpp"

// 共享资源，火车票
int tickets = 10000;

// 使用C++11的互斥量代替pthread的互斥量
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *getTicket(void *args)
{
    std::string username = static_cast<const char *>(args);

    while (true)
    {
        // 使用自定义的互斥量进行加锁
        LockGuard lockguard(&lock);

        if (tickets > 0)
        {
             std::this_thread::sleep_for(std::chrono::milliseconds(1254)); 
            std::cout << username << " 正在进行抢票: " << tickets << std::endl;
            tickets--;
        }
        else
        {
            break;
        }
    }

    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&t2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&t3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&t4, nullptr, getTicket, (void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}
